<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="keywords" label="关键字">
          <el-input
            v-model="queryParams.keywords"
            placeholder="角色名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>

        <el-form-item class="search-buttons">
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="hover" class="data-table">
      <div class="data-table__toolbar">
        <div class="data-table__toolbar--actions">
          <el-button type="success" icon="plus" @click="handleOpenDialog()">新增</el-button>
          <el-button
            type="danger"
            :disabled="ids.length === 0"
            icon="delete"
            @click="handleDelete()"
          >
            删除
          </el-button>
        </div>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="roleList"
        highlight-current-row
        class="data-table__content"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" type="index" width="60" align="center" />
        <el-table-column label="角色名称" prop="roleName" min-width="100" align="center" />
        <el-table-column label="角色编码" prop="roleCode" align="center" />
        <el-table-column label="状态" align="center">
          <template #default="scope">
            <el-tag v-if="scope.row.roleStatus === 1" type="success">正常</el-tag>
            <el-tag v-else type="error">停用</el-tag>
          </template>
        </el-table-column>
        <el-table-column fixed="right" align="center" label="操作" width="220">
          <template #default="scope">
            <el-button
              v-if="scope.row.id != 1"
              type="primary"
              size="small"
              link
              icon="position"
              @click="handleOpenAssignPermDialog(scope.row)"
            >
              分配权限
            </el-button>
            <el-button
              type="primary"
              size="small"
              link
              icon="edit"
              @click="handleOpenDialog(scope.row)"
            >
              编辑
            </el-button>
            <el-button
              type="danger"
              size="small"
              link
              icon="delete"
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="fetchData"
      />
    </el-card>

    <!-- 角色表单弹窗 -->
    <el-dialog
      v-model="dialog.visible"
      :title="dialog.title"
      width="800px"
      draggable
      :close-on-click-modal="false"
      @close="handleCloseDialog"
    >
      <el-form ref="roleFormRef" :model="formData" :rules="rules" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="formData.roleName" placeholder="请输入角色名称" />
        </el-form-item>

        <el-form-item label="角色编码" prop="roleCode">
          <el-input v-model="formData.roleCode" placeholder="请输入角色编码" />
        </el-form-item>
        <el-form-item label="状态" prop="roleStatus">
          <el-radio-group v-model="formData.roleStatus">
            <el-radio :value="1">正常</el-radio>
            <el-radio :value="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- <el-form-item label="角色权限" prop="permission">
          <el-row style="width: 600px">
            <el-col :span="24">
              <el-tree
                ref="treeRef"
                style="max-width: 600px"
                :data="treeList"
                show-checkbox
                node-key="id"
                :props="treeListProps"
                :default-checked-keys="checkedKeys"
                @check-change="treeCheckChange"
                @check="CheckChange"
                class="mt-5"
              ></el-tree>
            </el-col>
          </el-row>
        </el-form-item> -->
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <!-- <el-button type="primary" @click="getTest">获取树数据</el-button> -->

          <el-button type="primary" @click="addRole">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 权限分配 -->
    <el-dialog
      v-model="perDialog.visible"
      :title="perDialog.title"
      width="800px"
      draggable
      :close-on-click-modal="false"
      @close="closePerDialog"
    >
      <div style="height: 500px">
        <el-tree
          ref="treeRef"
          style="max-width: 600px"
          :data="treeList"
          show-checkbox
          node-key="id"
          :default-expanded-keys="launchedKeys"
          :props="treeListProps"
          class="mt-5"
          @check-change="treeCheckChange"
          @check="CheckChange"
        ></el-tree>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="preConfirmed">确 定</el-button>
          <el-button @click="preCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { useAppStore } from "@/store/modules/app.store";
import { DeviceEnum } from "@/enums/settings/device.enum";

import RoleAPI, { RolePageVO, RoleForm, RolePageQuery } from "@/api/system/role.api";
import MenuAPI from "@/api/system/menu.api";
import { log } from "console";
import { title } from "process";
import { template } from "lodash-es";

defineOptions({
  name: "Role",
  inheritAttrs: false,
});

const appStore = useAppStore();
const treeRef = ref<InstanceType<typeof ElTree>>();
const queryFormRef = ref();
const roleFormRef = ref();
const permTreeRef = ref();
const treeList = ref([]);
const launchedKeys = ref([]);
const loading = ref(false);
const ids = ref<number[]>([]);
const total = ref(0);
const getRoleId = ref(0);
const treeListProps = {
  children: "children",
  label: "menuName",
};
const queryParams = reactive<RolePageQuery>({
  pageNum: 1,
  pageSize: 10,
  roleName: "",
});
const isStrict = ref(false);
// 角色表格数据
const roleList = ref<RolePageVO[]>();
// 菜单权限下拉
const menuPermOptions = ref<OptionType[]>([]);
const preKeys = ref([]);
// 弹窗
const perDialog = reactive({
  title: "权限分配",
  visible: false,
});
const dialog = reactive({
  title: "",
  visible: false,
});
const rolePre = ref([]);
const drawerSize = computed(() => (appStore.device === DeviceEnum.DESKTOP ? "600px" : "90%"));
const checkedKeys = ref([2, 4, 5, 6]);
// 角色表单
const formData = reactive<RoleForm>({
  roleStatus: 1,
  roleName: "",
  roleCode: "",
  id: "",
});
const isSelected = ref(false);

function treeCheckChange(value, isAddValue, c) {
  // 获取当前节点的所有父节点（递归向上查找）
  isSelected.value = isAddValue;
  const parent = treeRef.value?.getNode(value.id);
  console.log("父节点111", isAddValue);

  // if (parent?.parent?.data.id != undefined) {
  //   if (isAddValue) {
  //     treeRef.value?.setChecked(parent?.parent?.data.id, true, false);
  //   }
  // }
}

function preCancel() {
  treeRef.value?.setCheckedKeys([], false);
  perDialog.visible = false;
}

function addRole() {
  roleFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const roleId = formData.id;
      if (roleId) {
        RoleAPI.update(formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        RoleAPI.create(formData)
          .then((res) => {
            console.log("角色名称", res, formData);
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

function preConfirmed() {
  if (preKeys.value.length > 0) {
    loading.value = true;
    const obj = {
      roleId: getRoleId.value,
      permissionId: preKeys.value,
    };
    RoleAPI.getRolePre(obj)
      .then((data) => {
        console.log("获取用户权限", data);
      })
      .finally(() => {
        loading.value = false;
      });
  } else {
    ElMessage.success("权限未修改");
  }
  perDialog.visible = false;
}
function getTest() {
  if (!treeRef.value) return;
  const allCheckedNode = treeRef.value.getCheckedNodes(false, true);
  console.log(allCheckedNode, "所有树绝点");
}
function CheckChange(a, value) {
  preKeys.value = [...value.checkedKeys, ...value.halfCheckedKeys];
  console.log("当前勾选的节点：", preKeys.value);
  const parent = treeRef.value?.getNode(a.id);
  if (isSelected.value == false) {
    treeRef.value?.setChecked(parent?.parent?.data.id, true, false);
  }
  console.log("父节点", parent?.parent?.data.id);
}
const rules = reactive({
  roleName: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
  roleCode: [{ required: true, message: "请输入角色编码", trigger: "blur" }],
  roleStatus: [{ required: true, message: "请选择状态", trigger: "blur" }],
});

// 选中的角色
interface CheckedRole {
  id?: string;
  name?: string;
}
const checkedRole = ref<CheckedRole>({});
const assignPermDialogVisible = ref(false);

const permKeywords = ref("");
const isExpanded = ref(true);

const parentChildLinked = ref(true);

// 获取数据
function fetchData() {
  loading.value = true;
  RoleAPI.getPage(queryParams)
    .then((data) => {
      console.log("获取用户权限", data);
      roleList.value = data.data.data;
      total.value = data.data.data.length;
    })
    .finally(() => {
      loading.value = false;
    });
}

//获取树形菜单
function getMenuList() {}

// 查询（重置页码后获取数据）
function handleQuery() {
  queryParams.pageNum = 1;
  fetchData();
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  fetchData();
}

// 行复选框选中
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

// 打开角色弹窗
function handleOpenDialog(row?: any) {
  dialog.visible = true;
  console.log(row);
  if (row.id) {
    dialog.title = "修改角色";
    formData.id = row.id;
    formData.roleName = row.roleName;
    formData.roleCode = row.roleCode;
    formData.roleStatus = row.roleStatus;
  } else {
    dialog.title = "新增角色";
  }
}

// 提交角色表单
function handleSubmit() {
  roleFormRef.value.validate((valid: any) => {
    if (valid) {
      loading.value = true;
      const roleId = formData.id;
      if (roleId) {
        RoleAPI.update(roleId, formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      } else {
        RoleAPI.create(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (loading.value = false));
      }
    }
  });
}

function closePerDialog() {
  perDialog.visible = false;
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;
  roleFormRef.value.resetFields();
  roleFormRef.value.clearValidate();
  formData.id = undefined;
  formData.roleStatus = 1;
}

// 删除角色
function handleDelete(roleId?: number) {
  const roleIds = [roleId || ids.value].join(",");
  if (!roleIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(
    () => {
      loading.value = true;
      RoleAPI.deleteByIds(roleIds)
        .then(() => {
          ElMessage.success("删除成功");
          handleResetQuery();
        })
        .finally(() => (loading.value = false));
    },
    () => {
      ElMessage.info("已取消删除");
    }
  );
}

async function getTreeList(roleId) {
  await MenuAPI.getOptions().then((data) => {
    treeList.value = data.data.data;
  });
  nextTick(async () => {
    const id = {
      id: roleId,
    };
    await RoleAPI.getRoleAuth(id)
      .then((data) => {
        if (data.data.code == 0) {
          const value = getAllChildreIds(data.data.data);
          launchedKeys.value = value;
          value.forEach((res) => {
            console.log("树", res);
            treeRef.value?.setChecked(res, true, false);
          });
        } else if (data.data.code == 1) {
          launchedKeys.value = [];
          treeRef.value?.setCheckedKeys([], false);
        }
      })
      .finally(() => {
        loading.value = false;
      });
  });
}
// getRoleAuth
// 打开分配菜单权限弹窗
async function handleOpenAssignPermDialog(row: RolePageVO) {
  getRoleId.value = row.id;
  const roleId = row.id;
  if (roleId) {
    loading.value = true;
    getTreeList(roleId);

    nextTick(() => {
      perDialog.visible = true;
    });
  }
}
function getAllChildreIds(node) {
  let ids = [];
  console.log("子节点", node);
  // 如果当前节点有子节点
  // if (node.children && node.children.length > 0) {
  node.forEach((child) => {
    // 收集当前子节点的 id
    ids.push(child.id);

    if (child.children && child.children.length > 0) {
      ids = [...ids, ...getAllChildreIds(child.children)];
    }
  });
  // }

  return ids;
}

// 分配菜单权限提交
function handleAssignPermSubmit() {
  const roleId = checkedRole.value.id;
  if (roleId) {
    const checkedMenuIds: number[] = permTreeRef
      .value!.getCheckedNodes(false, true)
      .map((node: any) => node.value);

    loading.value = true;
    RoleAPI.updateRoleMenus(roleId, checkedMenuIds)
      .then(() => {
        ElMessage.success("分配权限成功");
        assignPermDialogVisible.value = false;
        handleResetQuery();
      })
      .finally(() => {
        loading.value = false;
      });
  }
}

// 展开/收缩 菜单权限树
function togglePermTree() {
  isExpanded.value = !isExpanded.value;
  if (permTreeRef.value) {
    Object.values(permTreeRef.value.store.nodesMap).forEach((node: any) => {
      if (isExpanded.value) {
        node.expand();
      } else {
        node.collapse();
      }
    });
  }
}

// 权限筛选
watch(permKeywords, (val) => {
  permTreeRef.value!.filter(val);
});

function handlePermFilter(
  value: string,
  data: {
    [key: string]: any;
  }
) {
  if (!value) return true;
  return data.label.includes(value);
}

// 父子菜单节点是否联动
function handleparentChildLinkedChange(val: any) {
  parentChildLinked.value = val;
}

onMounted(() => {
  handleQuery();
});
</script>
